//
//  DZYPageCollectionLayout.swift
//  DZYPageView
//
//  Created by dongzhenyu on 2017/8/2.
//  Copyright © 2017年 dongzhenyu. All rights reserved.
//

import UIKit

class DZYPageCollectionLayout: UICollectionViewLayout {

    var sectionInset: UIEdgeInsets = UIEdgeInsets.zero
    var itemMargin: CGFloat = 0
    var lineMargin: CGFloat = 0
    var cols: Int = 4
    var rows: Int = 2
    
    fileprivate lazy var attibutes: [UICollectionViewLayoutAttributes] = [UICollectionViewLayoutAttributes]()
    fileprivate var totalWidth: CGFloat = 0
}


extension DZYPageCollectionLayout {
    override func prepare() {
        super.prepare()
        
        // 1.对collectionView进行校验
        guard let collectionView = collectionView else {
            return
        }
        
        // 2.获取collectionView里面有多少组数据
        let sections = collectionView.numberOfSections
        
        // 3. 遍历所有的组
        // 3.1 计算itemSize
        let itemW = (collectionView.bounds.width - sectionInset.left - sectionInset.right - itemMargin * CGFloat(cols - 1)) / CGFloat(cols)
        let itemH = (collectionView.bounds.height - sectionInset.top - sectionInset.bottom - lineMargin * CGFloat(rows - 1)) / CGFloat(rows)
        
        var previousNumofPage = 0 // 上一模块在第几页
        
        for section in 0..<sections {
            // 4.获取每组中有多少个items
            let items = collectionView.numberOfItems(inSection: section)
            
            // 5.遍历所有的items
            for item in 0..<items {
                // 6.根据section/items创建UICollectionViewLayoutAttributes
                let indexPath = IndexPath(item: item, section: section)
                let attibute = UICollectionViewLayoutAttributes(forCellWith: indexPath)
                
                // 7.给attibute中的frame进行赋值
                let currentPage = item / (cols * rows)
                let currentIndex = item % (cols * rows)
                
                let itemX: CGFloat = CGFloat(previousNumofPage + currentPage) * collectionView.bounds.width + sectionInset.left + (itemW + itemMargin) * CGFloat(currentIndex % cols)
                let itemY = sectionInset.top + (itemH + lineMargin) * CGFloat(currentIndex / cols)
                
                attibute.frame = CGRect(x: itemX, y: itemY, width: itemW, height: itemH)
                
                // 8.将attitude放入数组中
                attibutes.append(attibute)
            }
            
            previousNumofPage += (items - 1) / (cols * rows) + 1
            
        }
        
        totalWidth = CGFloat(previousNumofPage) * collectionView.bounds.width
    }
}

extension DZYPageCollectionLayout {
    override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
        
        return attibutes
    }
}

extension DZYPageCollectionLayout {
    
    override var collectionViewContentSize: CGSize {
        
        return CGSize (width: totalWidth, height: 0)
    }
}
